package com.cqjtu.tto.controller;

import com.cqjtu.tto.service.FileService;
import com.cqjtu.tto.vo.Results;
import com.cqjtu.tto.vo.params.FileParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;

@RestController
@Api(tags = "文件模块")
public class FileController {

    @Autowired
    FileService fileService;


    @ApiOperation(value = "文件上传")
    @RequestMapping(value = "upload", method = RequestMethod.POST)
    @ResponseBody
    public Results upload(@RequestParam("files") List<MultipartFile> files,String path,Long folderId,Long uploaderId) throws Exception {         //上传文件
        if (files.isEmpty()) {
            return Results.fail(-500,"未上传文件！");
        }
        FileParam fileParam = new FileParam(path,null,folderId,uploaderId);
        for (MultipartFile file : files) {
            String fileName1 = file.getOriginalFilename();
            fileParam.setFileName(fileName1);
            if (!file.isEmpty())
            {
                File dest = multipartFileToFile(file);                          //添加文件名后缀
                fileService.uploadFile(fileParam, dest);
            }
            else
            {
                return Results.fail(-500,"文件上传失败！");
            }
        }
        return Results.success("上传成功！");
    }



    public static File multipartFileToFile(MultipartFile multiFile) {
        // 获取文件名
        String fileName = multiFile.getOriginalFilename();
        System.out.println(fileName);
        // 获取文件后缀
//        String prefix = fileName.substring(fileName.lastIndexOf("."));
        // 若需要防止生成的临时文件重复,可以在文件名后添加随机码
        try {
            File file = File.createTempFile(fileName,"");
            multiFile.transferTo(file);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
